import sqlite3

def connect_db():
    try:
        conn = sqlite3.connect('trade_monitor.db')
        return conn
    except Exception as e:
        print(f"数据库连接失败: {e}")
        return None

def get_all_products(conn):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM products")
    return cursor.fetchall()

def insert_product(conn, data):
    cursor = conn.cursor()
    cursor.execute("INSERT INTO products (name, exchange_code, margin, stoploss, takeprofit, limit_stoploss, is_monitored) VALUES (?,?,?,?,?,?,?)", data)

def update_product(conn, product_id, data):
    update_query = "UPDATE products SET "
    update_query += ", ".join([f"{key} = ?" for key in data.keys()])
    update_query += " WHERE id = ?"
    values = list(data.values()) + [product_id]
    cursor = conn.cursor()
    cursor.execute(update_query, values)

def delete_product(conn, product_id):
    cursor = conn.cursor()
    cursor.execute("DELETE FROM products WHERE id = ?", (product_id,))

def get_monitored_products(conn):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM products WHERE is_monitored = 1")
    return cursor.fetchall()

def delete_product_by_name(conn, product_name):
    cursor = conn.cursor()
    cursor.execute("DELETE FROM products WHERE name = ?", (product_name,))

def get_product_by_id(conn, product_id):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
    return cursor.fetchone()

if __name__ == "__main__":
    conn = connect_db()
    if conn:
        test=get_monitored_products(conn)
        print(test)

